package com.mjlf.framework.mvc;

import com.mjlf.framework.mvc.eneity.ReqParams;
import com.mjlf.framework.mvc.eneity.RequestMethod;
import com.mjlf.framework.mvc.util.RequestManager;
import com.mjlf.framework.util.BeanManager;
import com.mjlf.framework.util.ReflectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Enumeration;

@WebServlet(urlPatterns = "/*", loadOnStartup = 1)
public class DispatcherServlet extends HttpServlet {
    private Logger logger = LoggerFactory.getLogger(DispatcherServlet.class);

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            BeanManager.init();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new ServletException("连接失败");
        }
        RequestManager.init();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {

            ReqParams reqParams = new ReqParams();
            Enumeration<String> paramKeys = req.getParameterNames();
            while (paramKeys.hasMoreElements()) {
                String key = paramKeys.nextElement();
                reqParams.addParam(key, req.getParameter(key));
            }

            //获取body中的参数
            BufferedReader br = req.getReader();
            parseParams(br, reqParams);

            String reqPath = req.getPathInfo();
            String reqMethod = req.getMethod().toUpperCase();
            RequestMethod requestMethod = RequestManager.getReqMethod(reqMethod, reqPath);

            if (requestMethod != null) {
                Method method = requestMethod.getReqMethod();
                Object object = requestMethod.getReqObj();
                ReflectionUtil.invokeMethod(object, method, req, resp, reqParams);
            } else {
                resp.sendError(404, "对应的请求处理:" + reqPath);
            }
        } catch (Exception e) {
            logger.error("请求处理过程中出现错误：" + e);
            resp.sendError(500, e.getMessage());
        }
    }

    public void parseParams(BufferedReader br, ReqParams params) throws IOException {
        String str;
        String all = "";
        int index = 0;
        String split = null;
        while ((str = br.readLine()) != null) {
            if (index == 0) {
                split = str;
                index++;
            }
            all += str;
        }

        String[] allKeyValue = all.split(split);
        if (allKeyValue != null) {
            for (String keyValue : allKeyValue) {
                if (keyValue.startsWith("Content-Disposition")) {
                    String kv = keyValue.split("; ")[1];
                    String[] kvs = kv.split("\"");
                    params.addParam(kvs[1], kvs[2]);
                }
            }
        }
    }
}
